package com.probiz.estoresa.system.web.action;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;

import com.probiz.estore.common.helper.ConfigUtil;
import com.probiz.estore.common.model.system.SmsQueue;
import com.probiz.estore.common.util.SmsUtil;
import com.probiz.estore.core.controller.GenericStoreAdminController;
import com.probiz.estore.core.search.SearchCriteria;
import com.probiz.estore.core.util.I18nUtil;
import com.probiz.estore.system.service.SmsQueueManager;
import com.probiz.estore.webapp.util.RequestUtil;

public class SmsQueueController extends GenericStoreAdminController<SmsQueue> {
    private SmsQueueManager smsQueueManager = null;

    public void setSmsQueueManager(SmsQueueManager inMgr) {
        this.smsQueueManager = inMgr;
    }

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.core.controller.GenericController#getEntityName(java.lang.Object)
	 */
	@Override
	protected String getEntityName(SmsQueue entity) {
		return entity.getSmsQueueName();
	}


	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.core.controller.BaseController#initController()
	 */
	@Override
	protected void initController() throws Exception {
		mgr = smsQueueManager;
	}
	
	@Override
	protected Map<String,String> getSortMap(){
		Map<String,String> sortMap = new HashMap<String,String>();
		sortMap.put("1", "convert_gbk(smsContent)");
		sortMap.put("2", "phoneNumbers");
		sortMap.put("3", "status");
		sortMap.put("4", "sendStatus");
		sortMap.put("5", "sendTime");
		sortMap.put("6", "createTime");
		return sortMap;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.core.controller.GenericController#preSave(javax.servlet.http.HttpServletRequest,
	 *      java.lang.Object, org.springframework.validation.BindException)
	 */
	@Override
	protected void preSave(HttpServletRequest request, SmsQueue entity, BindException errors) {
		entity.setStatus(SmsQueue.SMS_NOSEND);
	}
	
	public ModelAndView search(HttpServletRequest request,
			HttpServletResponse response) {
		SearchCriteria sc = createSearchCriteria(request);		
		List results = searchByCriteria(sc);
		return getModelAndView(listView, listModelName, results);
	}
	
	public ModelAndView smsLogout(HttpServletRequest request,
			HttpServletResponse response) {
		String serialNo = ConfigUtil.getInstance().getSerialNo();
		String password = ConfigUtil.getInstance().getSerialNoPassWord();
		int status = SmsUtil.getInstance().logout();
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("status", status);
		data.put("serialNo", serialNo);
		data.put("password", password);
		return getModelAndAjaxJsonView(data);
	}
	
	public ModelAndView smsLogin(HttpServletRequest request,
			HttpServletResponse response) {
		String serialNo = ConfigUtil.getInstance().getSerialNo();
		String password = ConfigUtil.getInstance().getSerialNoPassWord();
		int status = SmsUtil.getInstance().register();
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("status", status);
		data.put("serialNo", serialNo);
		data.put("password", password);
		return getModelAndAjaxJsonView(data);
	}
	
	public ModelAndView smsBalance(HttpServletRequest request,
			HttpServletResponse response) {
		String serialNo = ConfigUtil.getInstance().getSerialNo();
		String password = ConfigUtil.getInstance().getSerialNoPassWord();
		double balance = SmsUtil.getInstance().getBalance();
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("balance", balance);
		data.put("serialNo", serialNo);
		data.put("password", password);
		return getModelAndAjaxJsonView(data);
	}
	
	public ModelAndView sendSms2Form(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String ids[] = request.getParameterValues("multiIds");
		if(ConfigUtil.getInstance().isOpenMsgSend()){
			if (null != ids && ids.length > 0) {
				for (String id :ids) {
					if (StringUtils.isNotEmpty(id)) {
						SmsQueue sq = mgr.getById(new Integer(id));
						if (sq != null) {
							String phs[] = (sq.getPhoneNumbers()).split(",");
							String content = sq.getSmsContent();
							SmsQueue sqs = SmsUtil.getInstance().sendMsg(sq, phs, content);
							String str = sqs.getPhoneNumbers() + ": " + sqs.getSendStatus() + ".\n";
							saveMessage(request, str);
						}
					} else {
						String phstr = RequestUtil.getParameterNullSafe(request, "phoneNumbers");
						String content = RequestUtil.getParameterNullSafe(request, "smsContent");
						SmsQueue newSq = new SmsQueue();
						newSq.setSmsContent(content);
						newSq.setPhoneNumbers(phstr);
						newSq.setCustomerNames(phstr);
						newSq.setSendStatus("");
						newSq.setStatus(SmsQueue.SMS_NOSEND);
						newSq.setCreateTime(new Date());
						mgr.save(newSq);
						
						SmsQueue sqs = SmsUtil.getInstance().sendMsg(newSq, phstr.split(","), content);
						String str = sqs.getPhoneNumbers() + ": " + sqs.getSendStatus() + ".\n";
						saveMessage(request, str);
					}
				}
			} else {
				String phstr = RequestUtil.getParameterNullSafe(request, "phoneNumbers");
				String content = RequestUtil.getParameterNullSafe(request, "smsContent");
				SmsQueue newSq = new SmsQueue();
				newSq.setSmsContent(content);
				newSq.setPhoneNumbers(phstr);
				newSq.setCustomerNames(phstr);
				newSq.setSendStatus("");
				newSq.setStatus(SmsQueue.SMS_NOSEND);
				newSq.setCreateTime(new Date());
				mgr.save(newSq);
				
				SmsQueue sqs = SmsUtil.getInstance().sendMsg(newSq, phstr.split(","), content);
				String str = sqs.getPhoneNumbers() + ": " + sqs.getSendStatus() + ".\n";
				saveMessage(request, str);
			}
		}else{
			String str = I18nUtil.getInstance().getMessage("smsQueue.send.error");
			saveErrorMessage(request, str);
		}		
		return edit(request, response);
	}
	
	public ModelAndView sendSms2List(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String ids[] = request.getParameterValues("multiIds");
		StringBuffer buf = new StringBuffer();
		if(ConfigUtil.getInstance().isOpenMsgSend()){
			for (String id :ids) {
				SmsQueue sq = mgr.getById(new Integer(id));
				if (sq != null) {
					String phs[] = (sq.getPhoneNumbers()).split(",");
					String content = sq.getSmsContent();
					SmsQueue sqs = SmsUtil.getInstance().sendMsg(sq, phs, content);
					buf.append(sqs.getPhoneNumbers()).append(":").append(sqs.getSendStatus()).append(".<br />");
				}
			}
			saveMessage(request, buf.toString());
			return search(request, response);
		}else{
			saveErrorMessage(request, I18nUtil.getInstance().getMessage("smsQueue.send.error"));
			return search(request, response);
		}
	}

}
